package com.fzy.common.ftp;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;


/**
 * @describe 读取FTP上的文件
 * @auto zhoqunjie
 */
public class FtpUtil {

    private FTPClient ftpClient;
    private String strencoding;
    private String ip = "10.123.141.9";         // 服务器IP地址
    private String userName = "root";        // 用户名
    private String userPwd = "_#d@$4);kc_m(&);?d";  // 密码
    private int port = 22;                       // 端口号
    private static String path = "/";            // 读取文件的存放目录
    private static String LOCAL_CHARSET = "GBK";


    public FtpUtil() {
        this.reSet(ip, port, userName, userPwd, path);
    }

    public FtpUtil(String ip, int port, String userName, String userPwd, String path) {
        this.reSet(ip, port, userName, userPwd, path);
    }

    public void reSet(String ip, int port, String userName, String userPwd, String path) {
        // 以当前系统时间拼接文件名
        strencoding = "GBK";
        this.ip = ip;
        this.port = port;
        this.userName = userName;
        this.userPwd = userPwd;
        this.path = path;
        this.connectServer(ip, port, userName, userPwd, path);
    }

    /**
     * @param ip
     * @param port
     * @param userName
     * @param userPwd
     * @param path
     * @throws SocketException
     * @throws IOException     function:连接到服务器
     */
    public void connectServer(String ip, int port, String userName, String userPwd, String path) {
        ftpClient = new FTPClient();
        try {
            // 连接
            ftpClient.connect(ip, port);
            // 登录
            ftpClient.login(userName, userPwd);
            if (path != null && path.length() > 0) {
                // 跳转到指定目录

                ftpClient.changeWorkingDirectory(path);
            }
        } catch (SocketException e) {

        } catch (IOException e) {

        }
    }

    /**
     * @throws IOException function:关闭连接
     */
    public void closeServer() {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {

            }
        }
    }

    public List<String> list(String filePath) throws IOException {
        List<String> fileList = new ArrayList<String>();

        if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
            LOCAL_CHARSET = "UTF-8";
        }
        ftpClient.setControlEncoding(LOCAL_CHARSET);

        ftpClient.enterLocalPassiveMode();// 设置被动模式
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        // Use passive mode to pass firewalls.
        ftpClient.enterLocalPassiveMode();

        FTPFile[] ftpFiles = ftpClient.listFiles(filePath);
        int size = (ftpFiles == null) ? 0 : ftpFiles.length;
        for (int i = 0; i < size; i++) {
            try {
                FTPFile ftpFile = ftpFiles[i];
                if (ftpFile.isFile()) {
                    fileList.add(ftpFile.getName());
                }
            } catch (Exception e) {
                // TODO: handle exception
                continue;
            }

        }
        return fileList;
    }

    /**
     * @param path
     * @return function:读取指定目录下的文件名
     * @throws IOException
     */
    public List<String> getFileList(String path) {
        List<String> fileLists = new ArrayList<>();
        // 获得指定目录下所有文件名
        FTPFile[] ftpFiles = null;

        try {

            //设置编码方式
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.setControlEncoding(LOCAL_CHARSET);

            ftpClient.enterLocalPassiveMode();// 设置被动模式
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpFiles = ftpClient.listFiles(path);
            FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
            config.setServerLanguageCode("zh");
            ftpClient.configure(config);

            for (int i = 0; i < ftpClient.listNames().length; i++) {
                fileLists.add(ftpClient.listNames()[i]);
            }
//		  for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
//		   FTPFile file = ftpFiles[i];
//		   if (ftpClient.isConnected()) {
//			   if (file.isFile()) {
//		   	    fileLists.add(file.getName());
//			   }
//			   else if (file.isDirectory()) {    
//			       String currDirPath = path  + "/"+ file.getName(); 
//			       ftpClient.changeWorkingDirectory(currDirPath);  
//			       getFileList(currDirPath);
//			   }   
//		   } 
//		   else{
//			   System.out.println("连接失败");
//		   }
//		  }
        } catch (IOException e) {

        }

        return fileLists;
    }

    /**
     * @param fileName
     * @return function:从服务器上读取指定的文件
     * @throws ParseException
     * @throws IOException
     */
    public String readFile(String path, String fileName) throws ParseException {
        InputStream ins = null;
        StringBuilder builder = null;
        try {
            // 从服务器上读取指定的文件
            ftpClient.changeWorkingDirectory(path);
            ins = ftpClient.retrieveFileStream(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(ins, strencoding));
            String line;
            builder = new StringBuilder(150);
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append("\n");
            }
            reader.close();
            if (ins != null) {
                ins.close();
            }

            ftpClient.getReply();
        } catch (IOException e) {

        }
        return builder.toString();
    }

    public boolean downFile(String remotePath, String fileName, String localPath) {

        boolean result = false;
        try {
            int reply;
            ftpClient.setControlEncoding("utf-8");

            // 设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 获取ftp登录应答代码
            reply = ftpClient.getReplyCode();
            // 验证是否登陆成功
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("FTP server refused connection.");
                return result;
            }
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.setControlEncoding(LOCAL_CHARSET);

            ftpClient.enterLocalPassiveMode();// 设置被动模式
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
            config.setServerLanguageCode("zh");
            ftpClient.configure(config);
            // 转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(new String(remotePath.getBytes("utf-8"), "iso8859-1"));
            // 获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());
                    FileOutputStream os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(new String(ff.getName().getBytes("UTF-8"), "ISO-8859-1"), os);
                    os.close();
                }
            }

            ftpClient.logout();
            result = true;
        } catch (IOException e) {

        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * @param fileName function:删除文件
     */
    public void deleteFile(String fileName) {
        try {
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.setControlEncoding(LOCAL_CHARSET);

            ftpClient.enterLocalPassiveMode();// 设置被动模式
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_NT);
            config.setServerLanguageCode("zh");
            ftpClient.configure(config);
        } catch (IOException e) {

        }
    }

    public boolean uploadFile(String path, String fileName, InputStream input) {// 输入流

        boolean result = false;
        try {
            int reply;
            ftpClient.setControlEncoding("utf-8");

            // 设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 获取ftp登录应答代码
            reply = ftpClient.getReplyCode();
            // 验证是否登陆成功
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("FTP server refused connection.");
                return result;
            }
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.setControlEncoding(LOCAL_CHARSET);

            ftpClient.enterLocalPassiveMode();// 设置被动模式
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_NT);
            config.setServerLanguageCode("zh");
            ftpClient.configure(config);
            ftpClient.makeDirectory(path);
            ftpClient.changeWorkingDirectory(path);
            ftpClient.storeFile(new String(fileName.getBytes("UTF-8"), "ISO-8859-1"), input);
            input.close();

            ftpClient.logout();
            result = true;

        } catch (IOException e) {

        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    public boolean upLoadFromProduction(
            String path,
            String filename, // 上传到FTP服务器上的文件名
            String orginfilename // 输入流文件名
    ) {
        try {

            FileInputStream in = new FileInputStream(new File(orginfilename));
            boolean flag = uploadFile(path, filename, in);
            if (flag != true) {
                return false;
            }
        } catch (Exception e) {

        }
        return true;
    }

    public void downloadFile(String remoteDir, String filename, String localpath) {
        FTPClient ftpClient = new FTPClient();
        String hostName = ip;
        String username = userName;
        String password = userPwd;

        try {
            ftpClient.connect(hostName, 21);
            ftpClient.setControlEncoding("utf-8");
            ftpClient.login(username, password);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            FTPFile[] files = ftpClient.listFiles(remoteDir);


            //File file = new File(localpath+filename.substring(14, filename.length()));
            File file = new File(localpath + filename);
            FileOutputStream fos = new FileOutputStream(file);
            ftpClient.retrieveFile(remoteDir + "/" + new String(filename.getBytes("UTF-8"), "ISO-8859-1"), fos);
            fos.close();
        } catch (Exception e) {

        }
    }

    /**
     * @param args
     * @throws ParseException
     * @throws IOException
     */
    public static void main(String[] args) throws ParseException, IOException {

        //FtpUtil ftp = new FtpUtil("112.96.29.147", 21, "tmp_user", "tmp_!@#$user%^&", "/");
        FtpUtil ftp = new FtpUtil();
        //FtpUtil ftp36 = new FtpUtil("10.123.177.36", 21, "kefu", "DxraB1vF", "/");
        //File f= new File("D:/20160705test.txt");
        //ftp36.uploadFile("/20160705", "20160705test.txt", new FileInputStream(f));
        //String sb = ftp.readFile("/tmp_kls/tousu", "20151210-20151211ACCEPT-61.txt");
//	ftp.deleteFile("/tmp_kls/客服受理工单20151210.xlsx");
//		 ftp.downFile("/tingdianshitu", "20151217190818首页卡片接口数据结构.txt", "D:/");
    }
}
